package com.zboot.zbootadmin.project.system.login.controller;

import com.alibaba.fastjson.JSONObject;

import com.zboot.zbootadmin.common.constant.HttpStatus;
import com.zboot.zbootadmin.common.domain.ResponseData;
import com.zboot.zbootadmin.common.security.LoginUser;
import com.zboot.zbootadmin.common.security.service.SysLoginService;
import com.zboot.zbootadmin.common.security.service.SysPermissionService;
import com.zboot.zbootadmin.common.security.service.TokenService;
import com.zboot.zbootadmin.common.security.service.UserDetailsServiceImpl;
import com.zboot.zbootadmin.common.utils.ServletUtils;
import com.zboot.zbootadmin.project.system.login.dto.LoginDto;
import com.zboot.zbootadmin.project.system.menu.entity.SysMenu;
import com.zboot.zbootadmin.project.system.user.domain.SysUser;
import com.zboot.zbootadmin.project.system.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 登陆控制器
 */
@RestController
@CrossOrigin
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private UserService userService;



    /**
     * 登陆得到token
     *
     * @param loginDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登陆获取token")
    public ResponseData Login(@RequestBody LoginDto loginDto) {
        String token = loginService.login(loginDto.getUsername(), loginDto.getPassword(), loginDto.getCode(), loginDto.getUuid());
        ResponseData res = new ResponseData(HttpStatus.SUCCESS, "",token);
        return res;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/getInfo")
    @ApiOperation("获取用户信息")
    public ResponseData getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
       /* SysUser user = loginUser.getUser();*/
        SysUser user = userService.getById(loginUser.getUser().getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", user);
        jsonObject.put("roles", roles);
        jsonObject.put("permissions", permissions);
        return new ResponseData(HttpStatus.SUCCESS, jsonObject);
    }

}
